package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.common.exception.CustException;
import com.heima.model.behavior.dtos.ReadBehaviorDTO;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApReadBehavior;
import com.heima.model.common.constants.HotArticleConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.app.NewBehaviorDTO;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    private ApBehaviorEntryService apBehaviorEntryService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public ResponseResult readBehavior(ReadBehaviorDTO dto) {
        //校验参数
        if (dto==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //文章id 不能为空
        if (dto.getArticleId()==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"文章id不能为空");
        }

        //根据登录用户id 或设备id  查询行为实体数据   阅读操作 可不登录
        ApUser user = AppThreadLocalUtils.getUser();
        Integer userId = user.getId();
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(userId == null ? null : userId, dto.getEquipmentId());
        //判断阅读行为是否存在
        if (apBehaviorEntry==null){
           return   ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST,"实体获取失败");
        }

        //查询阅读行为
        ApReadBehavior readBehavior = mongoTemplate.findOne(Query.query(Criteria.where("entryId")
                .is(apBehaviorEntry.getId()).and("articleId")
                .is(dto.getArticleId())),
                ApReadBehavior.class);
        if (readBehavior!=null){
            //存在将阅读行为的count字段加1  并修改
            readBehavior.setCount((short)(readBehavior.getCount()+1));
            mongoTemplate.save(readBehavior);
        }else {
            //不存在创建阅读行为，并初始化count字段为1
            readBehavior=new ApReadBehavior();
            readBehavior.setCreatedTime(new Date());
            readBehavior.setEntryId(apBehaviorEntry.getId());
            readBehavior.setArticleId(dto.getArticleId());
            readBehavior.setUpdatedTime(new Date());
            readBehavior.setCount((short)1);

            mongoTemplate.save(readBehavior);
        }

        NewBehaviorDTO mess = new NewBehaviorDTO();
        mess.setType(NewBehaviorDTO.BehaviorType.VIEWS);
        mess.setArticleId(dto.getArticleId());
        mess.setAdd(1);
        rabbitTemplate.convertAndSend(HotArticleConstants.HOT_ARTICLE_SCORE_BEHAVIOR_QUEUE, JSON.toJSONString(mess));
        log.info("点赞行为 发送消息 ==>{}",JSON.toJSONString(mess));

        return ResponseResult.okResult();
    }
}
